package com.itany.shop.service.proxy;

import com.itany.shop.entity.User;
import com.itany.shop.exception.*;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.tran.TransactionManager;

/**
 * @author 石小俊
 * @date 2023年06月05日 15:25
 * 交叉业务逻辑,此处主要用于实现事务操作
 */
public class UserServiceProxy implements UserService {

    private TransactionManager tran = (TransactionManager) ObjectFactory.getObject("tran");
    private UserService userService = (UserService) ObjectFactory.getObject("userServiceTarget");

    @Override
    public void register(String username, String password, String phone, String address) throws ParameterErrorException, UserExistException {
        try {
            tran.begin();
            userService.register(username,password,phone,address);
            tran.commit();
        } catch (ParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (UserExistException e) {
            tran.rollback();
            throw e;
        } catch (DataAccessException e){
            tran.rollback();
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public User login(String username, String password) throws ParameterErrorException, UserNotExistException {
        try {
            tran.begin();
            User user = userService.login(username,password);
            tran.commit();
            return user;
        } catch (ParameterErrorException e) {
            tran.rollback();
            throw e;
        } catch (UserNotExistException e) {
            tran.rollback();
            throw e;
        } catch (DataAccessException e){
            tran.rollback();
            throw new ServiceException(e.getMessage());
        }
    }
}
